import json

import httpx


class OllamaQwen:
    def __init__(self, base_url="http://localhost:11434", model="qwen3:8b"):
        self.base_url = base_url
        self.model = model

    async def generate(self, prompt: str) -> str:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                f"{self.base_url}/api/generate",
                json={"model": self.model, "prompt": prompt}
            )
            response.raise_for_status()
            # 兼容多行 JSON（流式）
            result = ""
            for line in response.text.strip().splitlines():
                if not line.strip():
                    continue
                try:
                    data = json.loads(line)
                    if "response" in data:
                        result += data["response"]
                except Exception:
                    continue
            return result or "LLM无响应"
